package cn.com.nes.site.rocketmq.strategy;

import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MessageHandlerContext {

    private final Map<String, MessageHandler> handlerMap = new HashMap<>();

    // 动态注入所有的 MessageHandler 实现类
    @Autowired
    public MessageHandlerContext(List<MessageHandler> messageHandlers) {
        for (MessageHandler handler : messageHandlers) {
            String topic = extractTopicFromHandler(handler);
            if (topic != null) {
                handlerMap.put(topic, handler);
            }
        }
    }

    // 通过反射获取注解上的 topic
    private String extractTopicFromHandler(MessageHandler handler) {
        // 获取 handler 的 class 类型
        Class<?> handlerClass = handler.getClass();

        if (handlerClass.isAnnotationPresent(Topic.class)) {
            Topic topicAnnotation = handlerClass.getAnnotation(Topic.class);
            return topicAnnotation.value();
        }

        return null;
    }

    public void handleMessage(String topic, MessageExt message) {
        MessageHandler handler = handlerMap.get(topic);
        if (handler != null) {
            handler.handleMessage(message);
        } else {
            System.out.println("没有找到对应的处理策略，topic: " + topic);
        }
    }
}
